<template>
  <div class="channel-edit">
    <!-- 当前登陆用户已经订阅的频道 -->
    <div class="channel">
      <van-cell title="我的频道" :border="false">
        <van-button plain size="mini" type="danger" @click="editing =!editing">
          {{ editing? '取消' :'编辑' }}
        </van-button>
      </van-cell>
      <van-grid>
        <van-grid-item v-for="(item,index) in channels" :key="item.id">
          <span :class="{current:active === index}" @click="clickMychannel(index)">{{ item.name }}</span>
          <van-icon v-if="editing && index!==0" name="cross" class="btn" @click.self="clickDelChannel(item,index)" />
        </van-grid-item>
      </van-grid>
    </div>
    <!-- 当前登陆用户没有订阅的频道 -->
    <div class="channel">
      <van-cell title="可选频道" :border="false" />
      <van-grid>
        <van-grid-item v-for="item in optionalChannels" :key="item.id" @click="clickAddChannel(item)">
          <span>{{ item.name }}</span>
        </van-grid-item>
      </van-grid>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations } from 'vuex'
import { reqSetChannels } from '@/api/channels'
export default {
  name: 'ChannelEdit',

  props: {
    active: {
      type: Number,
      default: 0
    }
  },

  data() {
    return {
      editing: false
    }
  },

  computed: {
    ...mapState('channels', ['channels']),
    ...mapGetters('channels', ['optionalChannels'])
  },

  methods: {
    ...mapMutations('channels', ['addChannel', 'delChannel']),
    clickMychannel(index) {
      this.$emit('clickMychannel', index)
    },

    // 增加频道
    async clickAddChannel(item) {
      this.addChannel(item)
      const channelList = this.channels.map((item, index) => {
        return {
          id: item.id,
          seq: index
        }
      })
      await reqSetChannels(channelList)
    },

    // 减少频道
    async clickDelChannel(channel, index) {
      this.delChannel(channel)
      const channelList = this.channels.map((item, index) => {
        return {
          id: item.id,
          seq: index
        }
      })
      await reqSetChannels(channelList)

      if (this.active === index) {
        this.$emit('clickMychannel', 0)
      }
      if (index < this.active) {
        this.$emit('clickMychannel', this.active - 1)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.channel{
  padding:15px;
  font-size:14px;
  .current {
    color: #e5615b;
    font-weight: bold;
  }
  ::v-deep .van-button--mini {
    height: 22px;
    min-width: 50px;
  }
  .btn {
    position: absolute;
    top: 5px;
    right: 5px;
    font-size: 14px;
  }
}
</style>
